#! /bin/bash
#
# Author: Armando Basile, 2013
# 
# Please send feedback to armando@integrazioneweb.com
#
# /etc/init.d/sagentd
#
### BEGIN INIT INFO
# Provides:          sagentd
# Required-Start:    $local_fs $remote_fs $network $syslog $named
# Required-Stop:     $local_fs $remote_fs $network $syslog $named
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Agent for sensors
# Description:       Runs up the agent to manage sensors
### END INIT INFO

# Source function library.
. /lib/lsb/init-functions


SCRIPT_FILE="/var/sagent/engine/agent.py"
PID_FILE="/var/run/sagent.pid"
SERVICE=sagentd
RETVAL=0

# start engine
start() {
    # Check if service is already running
    if [ -f $PID_FILE ]
    then
        # Restart request
        restart
    else
        echo "Starting Server Sagent "    
        # Start the daemon
        python $SCRIPT_FILE start
        RETVAL=$?
        return $RETVAL
    fi
}



# stop engine
stop() {
    if [ -f $PID_FILE ]
    then
        # Stopping request
        echo "Stopping Server Sagent "
        # Stop the daemon
        python $SCRIPT_FILE stop
        RETVAL=$?
        return $RETVAL
    else
        # nothing
        echo "Server Sagent already stopped"
        exit 0
    fi

}



# restart engine
restart() {
    stop
    sleep 7 # required for socket server thread
    start
}



# check engine status
status() {
	if [ -f $PID_FILE ]
	then
		echo "Server Sagent is enabled"
	else
		echo "Server Sagent is disabled"
	fi
}



case "$1" in
  start)
    start
    log_end_msg "$RETVAL"
    ;;
  stop)
    stop
    log_end_msg "$RETVAL"
    ;;
  restart)
    restart
    log_end_msg "$RETVAL"
    ;;
  status)
    status
	;;
  *)
    # Refuse to do other stuff
    echo "Usage: $SERVICE {start|stop|restart|status}"
    exit 1
    ;;
esac

exit $RETVAL
